<?php

namespace App\Http\Controllers\Home;

use App\Model\UserModel;
use App\Http\Controllers\Controller;
use Validator;
use Illuminate\Http\Request;

class UserController extends Controller
{
    //登录
    public function login(Request $request) {
        if ($request->isMethod('post')) {
            //获取验证码
            $code = trim($request->input('code'));
            $rules = [ 'code' => 'captcha' ];
            $message = ['code.captcha' => '验证码输入不正确'];
            $validator = Validator::make(['code' => $code] , $rules , $message);

            //判断验证码
            if ($validator->fails()) {
                $msg = $validator->errors()->first();
                return [
                    'msg' => $msg,
                    'status' => 'fail'
                ];
            }
            
            //获取用户名及密码
            $username = trim($request->input('username'));
            $password = trim($request->input('password'));

            //用户名密码存入数据库
            $userModel = new UserModel;
            $res = $userModel->checkUser($username , $password);

            return $res;
        }
        return view('home.user.login');
    }

    //注册
    public function register(Request $request) {
        if ($request->isMethod('post')) {
            //获取验证码
            $code = trim($request->input('code'));
            $rules = [ 'code' => 'captcha' ];
            $message = ['code.captcha' => '验证码输入不正确'];
            $validator = Validator::make(['code' => $code] , $rules , $message);

            //判断验证码
            if ($validator->fails()) {
                $msg = $validator->errors()->first();
                return [
                    'msg' => $msg,
                    'status' => 'fail'
                ];
            }
            
            //获取用户名及密码
            $username = trim($request->input('username'));
            $password = trim($request->input('password'));

            //用户名密码存入数据库
            $userModel = new UserModel;
            $res = $userModel->insertUser($username , $password);

            if ( $res ) {
                session(['user' => $username]);
                return [ 'msg' => '注册成功' , 'status' => 'success'];
            } else {
                return [ 'msg' => '注册失败' , 'status' => 'fail'];
            }

        }
        return view('home.user.register');
    }

    //检验用户名是否存在
    public function checkName(Request $request) {
        $username = trim($request->input('param'));
        $userModel = new UserModel;
        $res = $userModel->checkName($username);

        if ($res['status'] == 'success') {
            return ['info' => '可以注册' , 'status' => 'y'];
        } else {
            return ['info' => '用户名已存在' , 'status' => 'n'];
        }
    }

    //用户退出
    public function logout() {
        session(['user' => null]);

        return redirect('/');
    }
}
